package com.neo.springcloud.alibaba.service.impl;

import com.neo.springcloud.alibaba.dao.OrderDao;
import com.neo.springcloud.alibaba.domain.Order;
import com.neo.springcloud.alibaba.service.AccountService;
import com.neo.springcloud.alibaba.service.OrderService;
import com.neo.springcloud.alibaba.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @ClassName: OrderServiceImpl
 * @Title: cloud2021
 * @Package: com.neo.springcloud.alibaba.service.impl
 * @Description:
 * @Author: Kisen
 * @Date: 2021/11/25 0:20
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    @Override
    @GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        String bizSeq = UUID.randomUUID().toString().replace("-", "");
        log.info("开始新建订单，bizSeq：" + bizSeq);
        order.setId(bizSeq);
        //1.新建订单
        orderDao.create(order);

        log.info("订单微服务开始调用库存，做扣减Count");
        //2.扣减库存
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("订单微服务开始调用库存，做扣减end");

        log.info("订单微服务开始调用账户，做扣减Money");
        //3.扣减库存
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("订单微服务开始调用账户，做扣减end");

        //4.修改订单状态，从0到1，1代表已完成
        log.info("修改订单状态开始");
        orderDao.update(order.getId(), 0);
        log.info("修改订单状态结束");

        log.info("下订单结束");
    }
}
